package edu.indiana.d2i.mapreduce;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputSplit;

public class HectorColumnFamilySplit extends InputSplit implements Writable {
	private List<ByteBuffer> keyList = null;
	private List<String> hosts = null;
	
	// get called by newInstance()
	protected HectorColumnFamilySplit() {}
	
	public HectorColumnFamilySplit(List<ByteBuffer> keyFilterList, List<String> hosts) {
		this.keyList = keyFilterList;
		this.hosts = hosts;
	}
	
	public List<ByteBuffer> getKeyList() {
		return keyList;
	}
	
	@Override
	public void readFields(DataInput in) throws IOException {
		int length = in.readInt();
		keyList = new ArrayList<ByteBuffer>();
		for (int i = 0; i < length; i++) { 
			int tmp = in.readInt();
			byte[] array = new byte[tmp];
			in.readFully(array);
			keyList.add(ByteBuffer.wrap(array));
		}
		length = in.readInt();
		hosts = new ArrayList<String>();
		for (int i = 0; i < length; i++) hosts.add(in.readUTF());
	}

	@Override
	public void write(DataOutput out) throws IOException {
		out.writeInt(keyList.size());
		for (ByteBuffer key : keyList) {
			out.writeInt(key.array().length);
			out.write(key.array());
		}
		out.writeInt(hosts.size());
		for (String host : hosts) out.writeUTF(host);
	}

	@Override
	// no use at this point
	public long getLength() throws IOException, InterruptedException {
		return Long.MAX_VALUE;
	}

	@Override
	public String[] getLocations() throws IOException, InterruptedException {
		return (hosts == null) ? new String[]{} : hosts.toArray(new String[hosts.size()]);
	}
	
	public String toString() {
		return " ";
	}
}
